# -*- encoding: utf-8 -*-
import time

from fabric.api import *
from fabric.colors import *
from setting import APIConfig as config


env.time = int(time.strftime("%Y%m%d")) * 100
env.roledefs = {
    'servers': config.SERVER_IPS
}

env.hosts = config.SERVER_IPS
env.port = '22'
env.user = 'root'


# jar到api服务器
@roles('servers')
def up_file_to_server(package):
    print yellow('<---- 开始上传 %s---->' % package)
    put('%s/%s' % (config.JUMP_TMP_FOLDER, package), '%s/%s' % (config.SERVER_TMP_FOLDER, package))
    print yellow('<---- 结束上传 %s---->' % package)


# 执行远程命令
@roles('servers')
def server_run_command(path, logoff):
    print red('开始执行<---------%s----------->命令' % path)
    with cd(path):
        print red(logoff)
        run(logoff)


@roles('servers')
def server_back_file():
    remote_file_path, remote_package_name = remote_file_not_exist_path(config.SERVER_BAK_PATH, env.time,
                                                                       config.SERVER_BAK_FOLDER + config.LOCAL_PACKAGE_SUFFIX)
    with cd(config.SERVER_BAK_PATH):
        command = 'tar -czvf %s %s' % (remote_package_name, config.SERVER_BAK_FOLDER)
        print red('开始执行<---------%s----------->命令' % command)
        run(command)


# 判断远程war包是否存在
@roles('servers')
def remote_file_not_exist_path(remote_package_dir, flag, local_package_name):
    path = '%s/%s-%s' % (remote_package_dir, flag, local_package_name)
    if int(run(" [ -e '%s' ] && echo 11 || echo 10" % path)) == 11:
        flag += 1
        return remote_file_not_exist_path(remote_package_dir, flag, local_package_name)
    else:
        return path, '%s-%s' % (flag, local_package_name)
